//
//  DownRadio.m
//  iNews
//
//  Created by lanou3g on 14-12-13.
//  Copyright (c) 2014年 张在青. All rights reserved.
//

#import "DownRadio.h"
#import "radioDetailDataModel.h"


static DownRadio *down = nil;

@implementation DownRadio

-(void)dealloc
{
    [_downTitle release];
    [_downUrl release];
    [_loadownArray release];
    [super dealloc];
    
}

-(void)encodeWithCoder:(NSCoder *)aCoder
{
    [aCoder encodeObject:self.downTitle forKey:@"title"];
}

-(id)initWithCoder:(NSCoder *)aDecoder
{
    self = [super init];
    if (self) {
        
        [aDecoder decodeObjectForKey:@"title"];
        
    }
    
    return self;
}

+(DownRadio *)downLoad
{
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        
        down = [[DownRadio alloc] init];
    });
    
    return down;
}

//获取并创建沙盒中的文件 ,这是一个私有方法.
-(NSString*)getPath
{
    NSString *document = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)[0];
    
    NSString *filePath = [document stringByAppendingString:@"/Radio"];
    
    NSString *name = [filePath stringByAppendingFormat:@"/%@.mp3",self.downTitle];
    return name;
}



-(void)loadDownWithUrl:(NSString *)url_str  appendPath:(NSString *)titleSting;
{
    //将值传给属性中的tetle 存起来;
    self.downTitle = titleSting;
    
    //调用title的归档方法
    [self archive:titleSting];
    
    if ([[NSFileManager defaultManager] fileExistsAtPath:[self getPath] ]) {
        
        NSLog(@"已经存在");
        
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:nil message:@"亲爱的已经存在了" delegate:nil cancelButtonTitle:nil otherButtonTitles:nil, nil] ;
        [alert show];
        [alert dismissWithClickedButtonIndex:0 animated:YES];
        [alert release];
        
    }else{
    
       NSURL *url = [NSURL URLWithString:url_str];
    
       NSURLRequest *request = [NSURLRequest requestWithURL:url cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:13];
    
       [NSURLConnection connectionWithRequest:request delegate:self];
    
    }
    
}
//给title 内容进行归档.
-(void)archive:(NSString *)titleString
{
    NSMutableArray *tempArray;
    
    int m = 0;
    
    if (self.loadownArray.count == 0) {
        tempArray = [NSMutableArray array];
        
    }else{
        tempArray = [NSMutableArray arrayWithArray:self.loadownArray];
        for (NSString *s  in tempArray) {
            if ([s isEqualToString:titleString]) {
                
                m = 1;
                break;
            }
            
        }
     
    }
    
    if (!m) {
        
        [tempArray addObject:self.downTitle];
        
        NSString *document = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)[0];
        
        NSString *filePath = [document stringByAppendingString:@"/RaioText.plist"];

        
        [NSKeyedArchiver  archiveRootObject:tempArray toFile:filePath];
        
        self.loadownArray = [NSMutableArray arrayWithArray:tempArray];
        
        [[NSNotificationCenter defaultCenter] postNotificationName:@"loadownArray" object:nil];
        
        
    }
   
}
//反归档
-(void)unarchive
{
    NSString *document = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)[0];
    
    NSString *filePath = [document stringByAppendingString:@"/RaioText.plist"];
    
    NSMutableArray *array = [NSKeyedUnarchiver unarchiveObjectWithFile:filePath];
    
    self.loadownArray = [NSMutableArray arrayWithArray:array];
    
}
//删除title
-(void)delete:(NSString *)titleString
{
    [self unarchive];
    
    if (self.loadownArray.count == 0) {
        NSLog( @"暂无收藏");
    }else{
        
        for (NSString *s  in self.loadownArray) {
            if ([s isEqualToString:titleString]){
                
                [self.loadownArray removeObject:s];
                
                break;
            }
            
        }
        NSString *document = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)[0];
        
        NSString *filePath = [document stringByAppendingString:@"/RaioText.plist"];
        
        [NSKeyedArchiver  archiveRootObject:self.loadownArray toFile:filePath];
        
        //删除后通知more 更新 ;
        
        [[NSNotificationCenter defaultCenter] postNotificationName:@"loadownArray" object:nil];
        
    }
    
}

#pragma mark 实现下载的几个方法
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
    self.loadData = [[NSMutableData alloc] init]  ;
   
    NSLog(@" //准备下载");
}


- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
    [self.loadData appendData:data];
    
    [self.loadData writeToFile:[self getPath] atomically:YES];
    
    NSLog(@"正在下载");
}

- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
    NSLog(@"下载完成");
    
    
    [self.loadData writeToFile:[self getPath] atomically:YES];
    
    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:nil message:@"亲爱的下载完成" delegate:nil cancelButtonTitle:nil otherButtonTitles:nil, nil];
    
    [alert show];
    [alert dismissWithClickedButtonIndex:0 animated:YES];
    [alert release];
    
}

-(void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
    UIAlertView *a = [[UIAlertView alloc] initWithTitle:nil message:@"下载出错了" delegate:nil
                                      cancelButtonTitle:nil otherButtonTitles:nil   , nil];
    NSLog(@"下载出错");
    
    [a show];
    [a dismissWithClickedButtonIndex:0 animated:YES];
}


@end
